<script>
    //获取cookie 通过document.cookie

    //如果要获取cookie或者设置cookie 不能是file协议

    // console.log(document.cookie);


    //设置cookie document.cookie = "xx"


    //cookie的存储形式是以'key=value'的形式来进行存储的

   
    document.cookie = "name=李雷" //设置了cookie
    document.cookie = "age=30" //设置了cookie
    document.cookie = "hobby=躺平" //设置了cookie

    //获取cookie

    console.log(document.cookie);

    //封装一个方法,用于去获取cookie

    function getCookie(key) {
        let val = '';//存储获取的cookey的value
        let cookies = document.cookie;
        // console.log(cookies);//name=李雷; age=30; hobby=躺平
        //先对字符串进行切割
        //因为字符串有空格,所以不能少了
        //console.log(cookies.replace(/\s/g, ""));//使用正则,全局匹配空格,匹配之后替换成"" 以此来去掉空格
        let cookieArr = cookies.split("; ")//["name=李雷", " age=30", " hobby=躺平"]
        // console.log(cookieArr);
        //遍历这个cookieArr 查找一下是不是包含我们传入的这个key
        cookieArr.forEach(item => {
            let c = item.split("=");
            // console.log(c);
            if (c[0] === key) {
                val = c[1]
            }
            //用传入的key和c[0]进行比较,如果相等,返回c[1]
        })
        return val;
    }

    console.log(getCookie('hobby'));
    console.log(getCookie('age'));
    console.log(getCookie('name') );
</script>